//
//  LoginViewController.m
//  JHFBaseProject
//
//  Created by 计海峰 on 16/4/20.
//  Copyright © 2016年 好牛. All rights reserved.
//

#import "LoginViewController.h"
#import "RegisterUserViewController.h"
#import "HNMainController.h"
#import "TTGlobalUICommon.h"
#import "ChatDemoHelper.h"
#import "HNForgetPwdController.h"


#import "AddressListController.h"

@interface LoginViewController (){
    NSMutableDictionary * _userInfo;
}

@end

@implementation LoginViewController

- (void)viewDidAppear:(BOOL)animated {
    [super viewDidAppear:animated];
    if([self.navigationController respondsToSelector:@selector(interactivePopGestureRecognizer)]) {
        self.navigationController.interactivePopGestureRecognizer.enabled = NO;
    }
}

- (void)viewDidDisappear:(BOOL)animated {
    [super viewDidDisappear:animated];
    //在其他离开改页面的方法同样加上下面代码
    if([self.navigationController respondsToSelector:@selector(interactivePopGestureRecognizer)]) {
        self.navigationController.interactivePopGestureRecognizer.enabled = YES;
    }
    
}

- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    
     [self.navigationController setNavigationBarHidden:YES animated:NO];
    
    
}

- (void)viewWillDisappear:(BOOL)animated {
    [super viewWillDisappear:animated];
    
    [self.navigationController setNavigationBarHidden:NO animated:YES];
}

- (void)viewDidLoad {
    [super viewDidLoad];
    
    CGColorSpaceRef colorSpaceRef = CGColorSpaceCreateDeviceRGB();
    CGColorRef color = CGColorCreate(colorSpaceRef, (CGFloat[]){226.0/255.0,226.0/255.0,226.0/255.0,1});
    
    _textView.layer.masksToBounds = YES;
    _textView.layer.cornerRadius = 1;
    _textView.layer.borderColor = color;
    _textView.layer.borderWidth = 1;
    
}



-(void)drawView{
    
    
    
    self.textView.layer.borderWidth = 0.5;
    self.textView.layer.borderColor = (__bridge CGColorRef _Nullable)RGB(237, 237, 237);
    
    self.LoginBtn.backgroundColor =  RGB(85, 206, 84);
    self.LoginBtn.layer.cornerRadius = 20;
    
    [self.quickBtn setTitleColor:RGB(113, 213, 112) forState:UIControlStateNormal];
    [self.forgetPwdBtn setTitleColor:RGB(171, 171, 171) forState:UIControlStateNormal];
    
    
    _phone.text = @"";
    _password.text = @"";
    
    
}

//-(void)loginSuccess:(NSDictionary *)resultData{
//    [USERDEFAULTS updateUserInfo:resultData];
//    [NotificationCenter postNotificationName:XXBLOGINSUCCESS object:nil];
//    [USER_DEFAULT setObject:USERDEFAULTS.userModel.userPhone forKey:LASTLOGINUSER];
//    S(@"登录成功");
//    [self.navigationController popViewControllerAnimated:YES];
//}


-(void)manageAddressAction{
    AddressListController *addressVC = [[AddressListController alloc]init];
    [self.navigationController pushViewController:addressVC animated:YES];
}
//登录
- (IBAction)login {
    
//    [self manageAddressAction];
// _phone.text = @"18056096068";
//    _password.text = @"123456";
    if (![_phone.text isMobileNumber]) {
        [self showHint:@"手机号码格式不正确"];
        return;
    }
    if (![_password.text isPassWord]) {
           [self showHint:@"密码长度在6~16位"];
        return;
    }
    NSDictionary *param = [NSDictionary dictionaryWithObjectsAndKeys:_phone.text,@"username",_password.text,@"password",@"0",@"isDoctor",nil];
    NSLog(@"param = %@",param);
    
    dispatch_async(dispatch_get_main_queue(),^{
        AFHTTPSessionManager *manager = [[AFHTTPSessionManager manager] initWithBaseURL:[NSURL URLWithString:url_Base]];
        manager.responseSerializer = [AFHTTPResponseSerializer serializer];
        [manager POST:url_Login parameters:param progress:^(NSProgress * _Nonnull downloadProgress) {
            
        } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
            NSError * error;
            
            NSDictionary * data=[NSJSONSerialization JSONObjectWithData:responseObject options:NSJSONReadingMutableLeaves error:&error];
            [self hideHud];
            if (error) {
                NSLog(@"====error1:%@",error);
                [self showHint:@"登录失败"];
                return;
            }
            NSLog(@"==dict:%@",data);
            
            NSString * result = [NSString stringWithFormat:@"%@",[data objectForKey:@"result"]];
            if ([result isEqualToString:@"1"]) {
                
                
                NSDictionary * obj = [NSDictionary dictionaryWithDictionary:[data objectForKey:@"obj"]];
                
                NSString *sessionId = [NSString stringWithFormat:@"%@",[obj objectForKey:@"sessionId"]];
                
                
                NSLog( @"sessionId = %@",sessionId);
                
                [AppConfig saveUserInfo:param];
                [Util addSessionId:sessionId];
                
                [self loginWithUsername:_phone.text password:@"111111"];
                
            }else{
                NSString * info = [NSString stringWithFormat:@"%@",[data objectForKey:@"msg"]];
                [self showHint:info];
            }
        } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull  error) {
            NSLog(@"====error:%@",error);
            [self hideHud];
            [self showHint:@"登录失败"];
        }];
    });



}

#pragma -mark 登录环信
//点击登陆后的操作
- (void)loginWithUsername:(NSString *)username password:(NSString *)password
{
    //当前的登录名
    
    [self showHudInView:self.view hint:nil];//NSLocalizedString(@"login.ongoing", @"Is Login...")
    //异步登陆账号
    __weak typeof(self) weakself = self;
    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
        
        EMError *error = [[EMClient sharedClient] loginWithUsername:username password:password];
        
        dispatch_async(dispatch_get_main_queue(), ^{
            [weakself hideHud];
            if (!error) {
                //设置是否自动登录
                [[EMClient sharedClient].options setIsAutoLogin:YES];
                
                //获取数据库中数据
                [self showHudInView:self.view hint:nil];
                dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
                    [[EMClient sharedClient] dataMigrationTo3];
                    dispatch_async(dispatch_get_main_queue(), ^{
                        [[ChatDemoHelper shareHelper] asyncGroupFromServer];
                        [[ChatDemoHelper shareHelper] asyncConversationFromDB];
                        [[ChatDemoHelper shareHelper] asyncPushOptions];
                        [self hideHud];
                        //发送自动登陆状态通知
                        [[NSNotificationCenter defaultCenter] postNotificationName:KNOTIFICATION_LOGINCHANGE object:@([[EMClient sharedClient] isLoggedIn])];
                        
                        //保存最近一次登录用户名
                        [weakself saveLastLoginUsername];
                        
                        [AppConfig saveUserInfo:_userInfo];
                        //                          [self downLoadUserInfo];
                        
                    });
                });
            } else {
                switch (error.code)
                {
                        //                    case EMErrorNotFound:
                        //                        TTAlertNoTitle(error.errorDescription);
                        //                        break;
                    case EMErrorNetworkUnavailable:
                        TTAlertNoTitle(NSLocalizedString(@"error.connectNetworkFail", @"No network connection!"));
                        break;
                    case EMErrorServerNotReachable:
                        TTAlertNoTitle(NSLocalizedString(@"error.connectServerFail", @"Connect to the server failed!"));
                        break;
                    case EMErrorUserAuthenticationFailed:
                        TTAlertNoTitle(error.errorDescription);
                        break;
                    case EMErrorServerTimeout:
                        TTAlertNoTitle(NSLocalizedString(@"error.connectServerTimeout", @"Connect to the server timed out!"));
                        break;
                    default:
                        TTAlertNoTitle(NSLocalizedString(@"login.fail", @"Login failure"));
                        break;
                }
            }
        });
    });

}

//忘记密码
- (IBAction)forgetPassword {
    HNForgetPwdController *forgetPwdVC = [[HNForgetPwdController alloc]init];
    [self.navigationController pushViewController:forgetPwdVC animated:YES];
}

//注册用户
- (IBAction)registerUser {
    RegisterUserViewController *registerUser = [[RegisterUserViewController alloc]init];
    [self.navigationController pushViewController:registerUser animated:YES];
}

//-(void)viewDidDisappear:(BOOL)animated{
//    H
//}

#pragma  mark - private
- (void)saveLastLoginUsername
{
    NSString *username = [[EMClient sharedClient] currentUsername];
    if (username && username.length > 0) {
        NSUserDefaults *ud = [NSUserDefaults standardUserDefaults];
        [ud setObject:username forKey:[NSString stringWithFormat:@"em_lastLogin_username"]];
        [ud synchronize];
    }
}


@end
